<template>
  <div class="document-view">
    <AxiomToolbar>
      <AxiomGroup v-if="knowledgeBase.name" align="center">
        <AxiomButton icon="arrow-left" text @click="goBack">返回知识库列表</AxiomButton>
        <AxiomDivider direction="vertical" />
        <AxiomTitle :title="knowledgeBase.name" :level="5"/>
      </AxiomGroup>
    </AxiomToolbar>
    <div class="p-4">
      <DocumentManagement
        v-if="!loading && (documents.length > 0 || isSearchActive)"
        :documents="documents"
        :pagination="pagination"
        :knowledge-base="knowledgeBase"
        :search-query="searchParams" 
        @refresh="fetchDocuments"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
        @search="handleSearch"
      />
      <DocumentUploadEmptyState
        v-else-if="!loading && documents.length === 0 && !isSearchActive"
        :knowledge-base="knowledgeBase"
        @refresh-documents="fetchDocuments"
      />
      <AxiomLoading v-if="loading" text="加载中..." class="mt-10" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  AxiomLoading,
  AxiomToolbar,
  AxiomGroup,
  AxiomButton,
  AxiomText,
  AxiomDivider,
} from 'axiom-view';
import DocumentManagement from './components/DocumentManagement.vue';
import DocumentUploadEmptyState from './components/DocumentUploadEmptyState.vue';
import { documentApi } from '@/api/knowledge/document.js';
import { knowledgeBaseApi } from '@/api/knowledge/knowledgeBase.js';

const props = defineProps({
  knowledgeBaseId: {
    type: String,
    required: true,
  },
});

const router = useRouter();

const knowledgeBase = ref({});
const documents = ref([]);
const loading = ref(true);

const searchParams = ref({
  file_name: '',
  status: null, // 修正：使用 null 作为初始值，语义更清晰
});

const isSearchActive = computed(() => {
  return (
    (searchParams.value.file_name && searchParams.value.file_name !== '') ||
    // 修正：正确处理数字 0 作为有效搜索条件的情况
    (typeof searchParams.value.status === 'number')
  );
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

async function fetchKnowledgeBaseDetails() {
  try {
    const res = await knowledgeBaseApi.getById(props.knowledgeBaseId);
    if (res.success) {
      knowledgeBase.value = res.data;
      // 动态设置当前路由的标题，面包屑会使用它
      if (router.currentRoute.value.meta) {
        router.currentRoute.value.meta.title = res.data.name;
      }
    }
  } catch (error) {
    console.error('获取知识库详情失败:', error);
  }
}

async function fetchDocuments() {
  loading.value = true;
  try {
    const params = {
      knowledge_base_id: props.knowledgeBaseId,
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };
    // 仅在搜索条件有值时才添加到参数中
    if (searchParams.value.file_name) {
      params.file_name = searchParams.value.file_name;
    }
    // 修正: 直接使用 status 的原始值 (number 或 null)
    if (searchParams.value.status !== null && searchParams.value.status !== undefined && searchParams.value.status !== '') {
      params.status = searchParams.value.status;
    }

    const res = await documentApi.listDocuments(params);
    if (res.success && res.data) {
      documents.value = res.data.items;
      pagination.total = res.data.total;
    } else {
      documents.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取文档列表失败:', error);
    documents.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
}

function handlePageChange(newPage) {
  pagination.currentPage = newPage;
  fetchDocuments();
}

function handleSizeChange(newSize) {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchDocuments();
}

function handleSearch(newSearchParams) {
  searchParams.value = newSearchParams;
  pagination.currentPage = 1;
  fetchDocuments();
}

function goBack() {
  router.push({ name: 'KnowledgeBases' });
}

onMounted(async () => {
  await fetchKnowledgeBaseDetails();
  await fetchDocuments();
});
</script>
